package com.pactera.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 17894 on 2021/3/12.
 */
public class DateUtil {

    private static Map<String, ThreadLocal<SimpleDateFormat>> map = new HashMap<String, ThreadLocal<SimpleDateFormat>>();
    private static final Object lock = new Object();

    /**
     * 日期单例，保证日期转换线程安全
     * @param pattern
     * @return
     */
    private static SimpleDateFormat getDateFormat(final String pattern) {
        ThreadLocal<SimpleDateFormat> t = map.get(pattern);
        if ( null == t) {
            synchronized (lock) {
                t = map.get(pattern);
                if (null == t) {
                    t = new ThreadLocal<SimpleDateFormat>() {
                        @Override
                        protected SimpleDateFormat initialValue() {
                            return new SimpleDateFormat(pattern);
                        }
                    };
                    map.put(pattern, t);
                }
            }
        }
        return t.get();
    }


    public static Date parse(String dateStr, String pattern) throws ParseException {
        return getDateFormat(pattern).parse(dateStr);
    }

    public static String format(Date date, String pattern) throws ParseException {
        return getDateFormat(pattern).format(date);
    }

}
